package com.baibei.ebec.home;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.AppLifecycle;
import com.baibei.basic.IPresenter;
import com.baibei.ebec.adapter.PopDialogAdapter;
import com.baibei.ebec.home.index.HomeIndexFragment;
import com.baibei.ebec.home.newIndex.NewHomeIndexFragment;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.ebec.user.mine.MineFragment;
import com.baibei.ebec.user.mine.MinePersonalFragment;
import com.baibei.ebec.user.mine.NewMineFragment;
import com.baibei.ebec.user.status.NotAllowFragment;
import com.baibei.ebec.welcome.FirstBuyGuideActivity;
import com.baibei.ebec.welfare.index.IndexWelfareFragment;
import com.baibei.ebec.widget.FragmentContainer;
import com.baibei.model.UserInfo;
import com.baibei.model.event.LoginEvent;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.order.list.IndexOrderFragment;
import com.baibei.product.quotation.RankingListFragment;
import com.baibei.quotation.event.IQuotationConnectEvent;
import com.baibei.quotation.event.QuotationConnectEvent;
import com.baibei.sdk.TokenEvent;
import com.baibei.ui.AppUI;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Route(path = AppRouter.ROUTER_MAIN)
public class HomeActivity extends BasicActivity implements OnTabSelectListener, IQuotationConnectEvent, View.OnTouchListener, View.OnClickListener, com.baibei.ebec.totrade.ToTradeFragment.OnTradeSuccessListener {


    @BindView(R.id.container)
    FragmentContainer mContainer;
    @BindView(R.id.tablayout)
    CommonTabLayout mTablayout;
    @BindView(R.id.iv_pop)
    protected ImageView ivPop;
    private List<Fragment> mFragmentList;
    private Fragment mIndexFragment;
    private Fragment mRankFragment;
    private Fragment mWelfareFragment;
    private Fragment mOrderFragment;
    private Fragment mMineFragment;
    private boolean isFirstStarted = true;

    // 登录过期处理
    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switchFragment();
            Activity activity = AppLifecycle.getDefault().getTopActivity();
            if (activity == null || !activity.getLocalClassName().contains("LoginActivity")) {
                AppUI.toastInCenter(getContext(), "登录过期，请重新登录");
                AppRouter.routeToLogin(HomeActivity.this);
            }
            return false;
        }
    });

    private boolean isClick;
    private int lastX;
    private int lastY;
    private long startTime;
    private int deltaX;
    private int deltaY;
    private long endTime;
    private int height;
    private String newVersion;
    private Dialog uDialog;
    private Dialog dialog;
    private long exitTime = 0;
    private ArrayList<Map<String, String>> maplist;
    private Fragment mNewIndexFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        postImei();
        postJiguangId();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        }
    }


    private void postJiguangId() {
//        SharedPreferences sp = getSharedPreferences("jiguang", MODE_PRIVATE);
//        String regId = sp.getString("regId", "-1");
//        String userId = sp.getString("userId", "-1");
//        String platform = sp.getString("platform", "");

        JPushInterface.init(getContext());
        String newRegId = JPushInterface.getRegistrationID(getContext());
//        LogUtils.e("jiguangpushid",newRegId);
        String newUserId = null;
        if (SessionManager.getDefault().getUser() != null) {
            newUserId = ((UserInfo) SessionManager.getDefault().getUser()).getUserId() + "";
        } else {
            newUserId = "0";
        }

        if (!"0".equals(newUserId)) {
            sendJiguangId(newRegId, newUserId);
        }
//        String newPlatform = "Android";

        //补充平台信息
//        if (!newPlatform.equals(platform)) {
//            sendJiguangId(newRegId, newUserId);
//        }

        //如果userId和regId有不一致
//        if (!userId.equals(newUserId) || !regId.equals(newRegId)) {
//            //且排除userId不为空，newUserId为空的情况，因为这个时候一般是用户未登录的情况
//            if (!userId.equals("-1") && newUserId.equals("0")) {
//                return;
//            }
//            sendJiguangId(newRegId, newUserId);
//        }
//        SharedPreferences.Editor editor = sp.edit();
//        editor.putString("regId", newRegId);
//        editor.putString("userId", newUserId);
//        editor.putString("platform", "Android");
//        editor.commit();
    }

    private void sendJiguangId(String newRegId, String newUserId) {
        final String url = BuildConfig.API_BASE_URL + "get/jgpush?userId=" + newUserId + "&pushId=" + newRegId + "&platform=Android";
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void postImei() {
        //判断这个页面是否是被销毁后第一次打开，还是从别的页面跳转过来的。
        if (!isFirstStarted) {
            return;
        }

        SharedPreferences sp = getSharedPreferences("imei", MODE_PRIVATE);
        String imei = sp.getString("imei", null);
        final String newImei = getimei();
        if (imei != null && !imei.equals(newImei)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("imei", newImei);
                    Gson gson = new Gson();
                    String s = gson.toJson(map);
                    RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                    String url = BuildConfig.API_BASE_URL + "get/DeviceId";
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .post(requestBody)
                            .url(url)
                            .build();
                    Call call = client.newCall(request);
                    try {
                        Response response = call.execute();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("imei", newImei);
        editor.commit();
        isFirstStarted = false;
    }

    private void popNewDialog() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getDialogInfo();
            }
        }).start();
    }

    private void popDialog() {

        //每天只弹一次弹窗
        SharedPreferences sp = getSharedPreferences("date", MODE_PRIVATE);
        String lastDate = sp.getString("date", "1970-01-01");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        String currentDate = sdf.format(new Date());

        if (lastDate.equals(currentDate)) {
            return;
        }

        SharedPreferences.Editor edit = sp.edit();
        edit.putString("date", currentDate);
        edit.commit();

//        if (!isFirstStarted) {
//            return;
//        }
        popNewDialog();

    }

    private void getDialogInfo() {

        TokenInfo userToken = SessionManager.getDefault().getUserToken();
        UserInfo userInfo = SessionManager.getDefault().getUser();
        HashMap<String, String> map = new HashMap<>();
        map.put("accessToken", userToken != null ? userToken.getAccessToken() : null);
        map.put("userId", userInfo != null ? "" + userInfo.getUserId() : null);
        Gson gson = new Gson();
        String s = gson.toJson(map);

        String dialogUrl = BuildConfig.API_BASE_URL + "tc/active";
//        String dialogUrl = "http://192.168.1.146:8080/adgox/tc/active";
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), s);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(dialogUrl)
                .build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            JSONObject json = new JSONObject(response.body().string());
            if (!"SUCCESS".equals(json.optString("code"))) {
                logout();
            }
            JSONArray arr = json.optJSONArray("data");
            maplist = new ArrayList<>();
            for (int i = 0; i < arr.length(); i++) {
                HashMap<String, String> m = new HashMap<>();
                JSONObject job = arr.getJSONObject(i);
                //背景图
                m.put("bjImg", job.optString("bjImg"));
                //跳转链接
                m.put("url", job.optString("url"));
                //判断是否显示券图，其实是判断是否为第一个弹窗
                if ("YES".equals(job.optString("show"))) {
                    //券图
                    m.put("ticketImg", job.optString("ticketImg"));
                    //领取状态
                    m.put("state", json.optString("state"));
                }
                maplist.add(m);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    finalPop();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (dialog != null){
            dialog.dismiss();
        }
    }

    private void finalPop() {
        dialog = new Dialog(getContext());
        Window window = dialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.dialog_pop);
        RecyclerView rv = dialog.findViewById(R.id.rv);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv.setLayoutManager(llm);
        PopDialogAdapter popDialogAdapter = new PopDialogAdapter(maplist, this);
        popDialogAdapter.setOnRecyclerViewItemClickListener(new PopDialogAdapter.onRecyclerViewItemClickListener() {
            @Override
            public void onClick(final View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_close:
                        dialog.dismiss();
                        break;
                    case R.id.tv_click:
                        if (!SessionManager.getDefault().isLogin()) {
                            AppRouter.routeToLogin(HomeActivity.this);
                            dialog.dismiss();
                            return;
                        }
                        String url = maplist.get(position).get("url");
                        AppRouter.routeToWeb(getContext(), url);
                        break;
                    case R.id.tv_state:
                        if (maplist.get(position).containsKey("state") && !"Y".equals(maplist.get(position).get("state"))) {

                            if (!SessionManager.getDefault().isLogin()) {
                                AppRouter.routeToLogin(HomeActivity.this);
                                dialog.dismiss();
                                return;
                            }
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    recTicket((TextView) view);
                                }
                            }).start();
                        }

                }
            }
        });
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        rv.setAdapter(popDialogAdapter);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 其实这个方法并不需要，因为只要用户首次登陆成功，就会自动发券到卡包，并不存在手动领券这种操作，
     * 所以这个方法其实是不会被调用的，但姑且还是写上吧
     */

    private void recTicket(final TextView view) {
        TokenInfo userToken = SessionManager.getDefault().getUserToken();
        HashMap<String, Object> map = new HashMap<>();
        map.put("exchange", BuildConfig.EXCHANGE);
        map.put("requestId", UUID.randomUUID().toString());
        if (SessionManager.getDefault().getUser() != null) {
            map.put("userId", ((UserInfo) SessionManager.getDefault().getUser()).getUserId() + "");
        } else {
            map.put("userId", "0");
        }
        map.put("platform", "server");
        map.put("deviceId", "BB-" + System.currentTimeMillis() + "-" + UUID.randomUUID().toString());
        map.put("timestamp", "" + System.currentTimeMillis());
        map.put("version", getVersion());
        map.put("memberChannel", ApiConstant.MEMBER_CHANNEL);
        map.put("appKey", BuildConfig.APPKEY);
        map.put("accessToken", userToken.getAccessToken());
        map.put("refreshToken", userToken.getRefreshToken());
        Gson gson = new Gson();
        String s = gson.toJson(map);

        OkHttpClient client = new OkHttpClient();
        String url = BuildConfig.API_BASE_URL + "QueryTC/ticket";
        RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            JSONObject json = new JSONObject(response.body().string());
            if (!"SUCCESS".equals(json.optString("code"))) {

                return;
            }
            JSONObject data = json.optJSONObject("data");
            final String state = data.optString("state");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ("Y".equals(state)) {
                        Toast.makeText(getContext(), "领取成功，请去卡包查看", Toast.LENGTH_LONG).show();
                        view.setText("已领取");
                        view.setTextColor(getContext().getResources().getColor(R.color.green));
                        return;
                    }
                    Toast.makeText(getContext(), "领取失败", Toast.LENGTH_LONG).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private String getimei() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
            String imei = telephonyManager.getDeviceId();
            return imei;
        } else {
            return null;
        }
    }

    @Override
    public IPresenter getBasicPresenter() {
        return null;
    }

    @Override
    protected void onDestroy() {
        mHandler.removeMessages(0);
        super.onDestroy();
        // 断开行情
        QuotationManager.getInstance().destroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {

        //初始化tablayout
        ArrayList<CustomTabEntity> entities = new ArrayList<>();
        for (MenuType menuType : MenuType.values()) {
            entities.add(new TabEntity(menuType));
        }

        mTablayout.setTabData(entities);

        mFragmentList = new ArrayList<>();

        mIndexFragment = HomeIndexFragment.newInstance();
        mNewIndexFragment = NewHomeIndexFragment.newInstance();
        mRankFragment = RankingListFragment.newInstance();
//        Fragment rankingFragment = new RankingFragment();
        mOrderFragment = createOrderFragment();
        mMineFragment = createMineFragment();
        mWelfareFragment = IndexWelfareFragment.newInstance();
//        mFragmentList.add(mIndexFragment);
        mFragmentList.add(mNewIndexFragment);
        mFragmentList.add(mRankFragment);
        mFragmentList.add(mWelfareFragment);
//        mFragmentList.add(rankingFragment);
        mFragmentList.add(mOrderFragment);
        mFragmentList.add(mMineFragment);

        //设置宽度
        mContainer.setOffscreenPageLimit(5);
        mContainer.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
        mTablayout.setOnTabSelectListener(this);

//        //打开时首页展示排行榜
//        mContainer.setCurrentItem(1);
//        mTablayout.setCurrentTab(1);

        WindowManager wm = getWindowManager();
        height = wm.getDefaultDisplay().getHeight();

        ivPop.setOnTouchListener(this);

        //检查更新
        checkUpdate();
    }

    private void checkUpdate() {


        new Thread(new Runnable() {
            @Override
            public void run() {
                String checkUrl = BuildConfig.API_BASE_URL + "validate/version";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(checkUrl)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    String code = jsonObject.optString("code");
                    if (!"SUCCESS".equals(code)) {
                        return;
                    }
                    JSONObject job = jsonObject.optJSONObject("data");
                    newVersion = job.optString("androidVersion");
                    if (getVersion().equals(newVersion)) {
                        popDialog();
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showUpdateDialog();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showUpdateDialog() {
        uDialog = new Dialog(getContext());
        Window window = uDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        uDialog.setContentView(R.layout.dialog_update);
        TextView newVer = uDialog.findViewById(R.id.tv_newVer);
        TextView cuVer = uDialog.findViewById(R.id.tv_cuVer);
        TextView tvConfirm = uDialog.findViewById(R.id.tv_confirm);
        TextView tvCancel = uDialog.findViewById(R.id.tv_cancel);

        newVer.setText("最新版本:" + newVersion);
        cuVer.setText("当前版本:" + getVersion());

        tvConfirm.setOnClickListener(this);
        tvCancel.setOnClickListener(this);

        uDialog.setCanceledOnTouchOutside(false);

        uDialog.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_confirm:
                toUpdate();
                uDialog.dismiss();
                break;
            case R.id.tv_cancel:
                uDialog.dismiss();
        }
    }

    private void toUpdate() {
        if (isYYBExist()) {
            // 市场存在，唤醒应用宝
            launchAppDetail(getApplicationContext(), "com.shzstr.diandiantaojin", "com.tencent.android.qqdownloader");
        } else {
            //市场不存在，跳转浏览器
            Uri uri = Uri.parse("http://a.app.qq.com/o/simple.jsp?pkgname=com.shzstr.diandiantaojin");
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(it);
        }
    }

    private void launchAppDetail(Context applicationContext, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg))
                intent.setPackage(marketPkg);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            applicationContext.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isYYBExist() {
        final PackageManager packageManager = getContext().getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.android.qqdownloader")) {
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    public void onTabSelect(int position) {
//        if (position == 2){
//            return;
//        }
        //跳转到订单页面，先判断是否登录,没有登录则跳去登录

        if (mFragmentList.get(position).equals(mOrderFragment) && !SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(this, AppRouter.REQ_LOGIN_BY_ORDERLIST);
            //样式
            mTablayout.setCurrentTab(mContainer.getCurrentItem());
            return;
        }
        if (mFragmentList.get(position).equals(mWelfareFragment) && !SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(this, AppRouter.REQ_LOGIN_BY_WELFARE);
            mTablayout.setCurrentTab(mContainer.getCurrentItem());
            return;
        }
        mContainer.setCurrentItem(position, false);
    }

    @Override
    public void onTabReselect(int position) {
    }

    @Override
    protected void onActivityResultOK(int requestCode, Intent data) {
        super.onActivityResultOK(requestCode, data);
        if (requestCode == AppRouter.REQ_LOGIN) {
            switchFragment();
        } else if (requestCode == AppRouter.REQ_LOGIN_BY_ORDERLIST) {
            //如果是订单登录成功，返回订单列表界面
            int position = mFragmentList.indexOf(mOrderFragment);
            mContainer.setCurrentItem(position, false);
            mTablayout.setCurrentTab(position);
        } else if (requestCode == AppRouter.REQ_LOGIN_BY_WELFARE) {
            //如果是福利页面登录成功，返回福利页面
            int positon = mFragmentList.indexOf(mWelfareFragment);
            mContainer.setCurrentItem(positon);
            mTablayout.setCurrentTab(positon);
        }
    }

    /**
     * 登录成功后，切换我的页面
     */
    private void switchFragment() {

//        // 切换订单页面
//        int orderIndex = mFragmentList.indexOf(mOrderFragment);
//        mFragmentList.remove(mOrderFragment);
//        mOrderFragment = null;
//        mOrderFragment = createOrderFragment();
//        mFragmentList.add(orderIndex, mOrderFragment);
//
        // 切换我的页面
        int mineIndex = mFragmentList.indexOf(mMineFragment);
        mFragmentList.remove(mMineFragment);
        mMineFragment = null;
        mMineFragment = createMineFragment();
        mFragmentList.add(mineIndex, mMineFragment);
//
        mContainer.getAdapter().notifyDataSetChanged();

    }

    private Fragment createOrderFragment() {
        if (!SessionManager.getDefault().isLogin()) {
            return IndexOrderFragment.newInstance();
        }
        UserInfo user = SessionManager.getDefault().getUser();
        if (user.getUserType() == UserInfo.USER_TYPE_ENTERPRISE) {
            return NotAllowFragment.newInstance(null);
        }
        return IndexOrderFragment.newInstance();
    }

    /**
     * 根据用户状态创建我页面
     */
    private MineFragment createMineFragment() {
        if (!SessionManager.getDefault().isLogin()) {
            return MineFragment.newInstance();
        }
        UserInfo user = SessionManager.getDefault().getUser();
        int userType = user.getUserType();
        MineFragment fragment;
        if (userType == UserInfo.USER_TYPE_PERSONAL) {
            fragment = MinePersonalFragment.newInstance();
        } else {
            fragment = MineFragment.newInstance();
        }
        return fragment;
//        return NewMineFragment.newInstance();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //跳对应fragment页面
        if (intent.hasExtra("position")) {
            int position = intent.getIntExtra("position", 0);
            mContainer.setCurrentItem(position, false);
            mTablayout.setCurrentTab(position);
            return;
        }
        if (intent.hasExtra("flag")) {
            String flag = intent.getStringExtra("flag");
            if ("share".equals(flag)) {
                //跳个人中心自动分享[]
                mContainer.setCurrentItem(4);
                mTablayout.setCurrentTab(4);
                Bundle bundle = new Bundle();
                bundle.putString("flag", "share");
                mMineFragment.setArguments(bundle);
                return;
            }
        }
    }

    @Subscribe
    public void onEvent(LoginEvent event) {

        // 刷新fragment
        switchFragment();
        if (event.isLogin() && SessionManager.getDefault().isLogin()) {
            TokenInfo token = SessionManager.getDefault().getUserToken();
            QuotationManager.getInstance().bindUserInfo(token.getAccessToken());
            postJiguangId();
            //注册成功才弹出购买引导
            if (event.isRegister()) {
//                ivPop.performClick();
//                Intent intent = new Intent(HomeActivity.this, FirstBuyGuideActivity.class);
//                startActivity(intent);
                AppRouter.routeToFirstBuy(getContext());
            }
        }
    }

    /**
     * 按两次返回键退出
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (System.currentTimeMillis() - exitTime >= 2000) {
            Toast.makeText(getContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    /**
     * 登录事件
     */
    @Subscribe
    public void onEvent(TokenEvent event) {
        // 登录过期
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 2000);
    }

    /**
     * 行情连接断开事件
     */
    @Override
    @Subscribe
    public void onEvent(QuotationConnectEvent event) {
        if (event.isConnected()) {
            QuotationManager.getInstance().bindExchange(BuildConfig.EXCHANGE);
        }
        if (event.isConnected() && SessionManager.getDefault().isLogin()) {
            TokenInfo token = SessionManager.getDefault().getUserToken();
            QuotationManager.getInstance().bindUserInfo(token.getAccessToken());
        }
    }

    @OnClick(R.id.iv_pop)
    public void onViewClicked() {
        popNewDialog();
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        int startX = (int) ivPop.getX();
        int startY = (int) ivPop.getY();
        int action = motionEvent.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isClick = false;
                lastX = (int) motionEvent.getRawX();
                lastY = (int) motionEvent.getRawY();
                startTime = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_MOVE:
                isClick = true;
                int currentX = (int) motionEvent.getRawX();
                Log.i("currentX", "" + currentX);
                int currentY = (int) motionEvent.getRawY();
                Log.i("currentY", "" + currentY);

                deltaX = currentX - lastX;
                deltaY = currentY - lastY;

                lastX = currentX;
                lastY = currentY;

                ivPop.setX(startX + deltaX);

                if ((startY + deltaY) > (height - dip2px(getContext(), 54))) {
                    ivPop.setY(height - dip2px(getContext(), 100));
                } else if ((startY + deltaY) < dip2px(getContext(), 28)) {
                    ivPop.setY(dip2px(getContext(), 13));
                } else {
                    ivPop.setY(startY + deltaY);
                }
//                ivPop.setY(startY+deltaY);
                break;
            case MotionEvent.ACTION_UP:
                endTime = System.currentTimeMillis();
                if ((endTime - startTime) > 0.2 * 1000l) {
                    isClick = true;
                } else {
                    isClick = false;
                }
                ivPop.setX(0);
//                ivPop.setY((int)motionEvent.getY());
                if ((startY + deltaY) > (height - dip2px(getContext(), 100))) {
                    ivPop.setY(height - dip2px(getContext(), 100));
                } else if ((startY + deltaY) < dip2px(getContext(), 28)) {
                    ivPop.setY(dip2px(getContext(), 13));
                } else {
                    ivPop.setY(startY + deltaY);
                }
        }
        return isClick;
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @OnClick(R.id.iv_mid)
    public void onMidClicked() {
        mTablayout.setCurrentTab(2);
        mContainer.setCurrentItem(2, false);
    }

    @Override
    public void onTradeSuccess() {
        mTablayout.setCurrentTab(3);
        mContainer.setCurrentItem(3, false);
    }

    /**
     * 管理布局
     * 适配器
     */
    private class ViewPagerAdapter extends FragmentStatePagerAdapter {

        ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }

    private String getVersion() {
        try {
            return getContext().getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }
}
